package com.demo.javase.day51;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Date类示例演示
 *
 * @author bug菌
 * @version 1.0
 * @date 2023/10/16 17:12
 */
public class DateTest {

    public static void main(String[] args) {

        // 创建当前时间的Date对象
        Date date = new Date();
        // 获取年、月、日、时、分、秒
        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        int day = date.getDate();
        int hour = date.getHours();
        int minute = date.getMinutes();
        int second = date.getSeconds();
        System.out.printf("当前时间：%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second);

        // 将Date对象格式化成字符串
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = sdf.format(date);
        System.out.println("当前时间：" + str);

        // 获取当前时间的时间戳
        long timestamp = System.currentTimeMillis();
        System.out.println("当前时间戳：" + timestamp);

        // 将时间戳转换成Date对象
        Date date2 = new Date(timestamp);
        System.out.println("时间戳转换成Date对象：" + date2);

        // 将Date对象转换成时间戳
        long timestamp2 = date2.getTime();
        System.out.println("Date对象转换成时间戳：" + timestamp2);

    }
}
